# 异常
# 常见异常
console.log(a); // Uncaught ReferenceError: a is not defined.跑异常后面的代码其实不会执行了
var emp = undefined;
console.log(emp.name); // Uncaught TypeError: Cannot read property 'name' of undefined
# try...catch
try {
console.log(a);
} catch (error) {
console.error(error); // Uncaught ReferenceError: a is not defined
} finally {
console.log("总会执行");
}
try {
var emp = undefined;
console.log(emp.name);
} catch (error) {
console.error(error); // TypeError: Cannot read property 'name' of undefined
} finally {
console.log("总会执行");
}
# throw
class ApiError extends Error {
constructor(url, ...params) {
super(...params);
this.name = "ApiError";
this.url = url;
}
}
function fetchData() {
console.log("获取数据...");
console.log(a);
throw new ApiError("/api/hello", "404"); //不推荐,应该继承异常对象
}
try {
fetchData();
} catch (error) {
if (error instanceof ReferenceError) {
console.log("程序异常");
} else if (error instanceof ApiError) {
console.error(error);
console.error(error.name); // ApiError
console.error(error.message); // 404
console.error(error.url); // /api/hello
}
}